define(function () {
  /**
   * 计算多边形实体面积
   * @param {Cesium.Viewer} viewer 基本视图
   * @param {Cesium.ScreenSpaceEventHandler} handler 屏幕监听事件
   * @param {ReminderPanel} reminder 信息提示类
   * @param {Cesium.CustomDataSource}measureEntities 标绘实体集合
   */
  let calcArea = function (viewer, handler, reminder, measureEntities) {
    let activeShapePoints = []                      //标绘点集合

    /**
     *添加多边形实体
     *@param {Cesium.Cartesian3 []} positionData 线段数组
     */
    function drawShape(positionData) {
      return measureEntities.entities.add({
        polygon: {
          hierarchy: positionData,
          material: new Cesium.ColorMaterialProperty(
            Cesium.Color.WHITE.withAlpha(0.4)
          ),
        },
      })
    }

    /**
     *添加点
     *@param {Cesium.Cartesian3} worldPosition
     */
    function createPoint(worldPosition) {
      return measureEntities.entities.add({
        position: worldPosition,
        point: {
          color: Cesium.Color.WHITE,
          pixelSize: 5,
        },
      })
    }

    //左键点击，绘画并提醒
    handler.setInputAction((event) => {
      let earthPosition = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid)
      if (activeShapePoints.length === 0) {
        createPoint(earthPosition)
      }
      activeShapePoints.push(earthPosition)
      drawShape(activeShapePoints)
      reminder.show((polgyonArea(activeShapePoints) / 1000000.0).toFixed(4) + ' 平方千米')
      createPoint(earthPosition)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    handler.setInputAction(function (event) {
      activeShapePoints = []
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

    //求二维面积
    function polgyonArea(points) {
      let area = 0
      for (let i = 0; i < points.length; i++) {
        let j = (i + 1) % points.length
        area += points[i].x * points[j].y
        area -= points[i].y * points[j].x
      }
      area /= 2
      return Math.abs(area)
    }
  }
  return calcArea
})